package com.newopenlab.hmc.util;

import java.text.ParseException;

import com.newopenlab.hmc.biz.*;

public class ActionParser {
	
	public BaseHand bh=null;
	public BasicParser basicParser=null;
	public ActionParser(){
		
	}
	
	public WayAction parse(String line){
		WayAction wa=null;
		String player=this.basicParser.getStringBefore(line, BasicParser.HEADER_ACTION_PLAYER_POST);
		if(player!=null){
			wa=new WayAction();
			wa.player=this.bh.getPlayerByName(player);
			for(Action a:Action.values()){
				if(line.contains(a.getVerb())){
					wa.action=a.getName();
					if(a==Action.RAISE){
						//wa.chips=this.basicParser.
						String aux=this.basicParser.getStringAfter(line, a.getVerb(),1);
						String[] v=aux.split(" ");
						try {
							wa.chips=this.basicParser.nf.parse(v[2].substring(1)).doubleValue();
						} catch (Exception e) {
							System.out.println(" errore su :"+v[2]);
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}else if(a.hasArgument()){
						try {
							wa.chips=this.basicParser.nf.parse(this.basicParser.getStringAfter(line, a.getVerb(),2)).doubleValue();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					//System.out.println(wa.way+" "+wa.player.name+" "+wa.action+" "+wa.chips);
				}
			}
			
		}
		boolean toBeCancelled=false;
		if(wa!=null){
			if(wa.player==null){
				toBeCancelled=true;
				//System.out.println("ac strana "+line);
			}
			if(wa.action==null){
				toBeCancelled=true;
				//System.out.println("ac strana "+line);
			}
		}
		if(toBeCancelled){
			wa=null;
		}
		return wa;
	}
	
	public Boolean filterUncalledBets(String line){
		Boolean res=false;
		String uBets=this.basicParser.getStringIn(line, BasicParser.HEADER_UNCALLED_BET_PRE, BasicParser.HEADER_UNCALLED_BET_POST, 1);
		if(uBets!=null){
			try {
				String name=this.basicParser.getStringAfter(line,  BasicParser.HEADER_UNCALLED_BET_POST);
				WayAction wa=new WayAction();
				wa.action=Action.BET.getName();
				wa.player=this.bh.getPlayerByName(name);
				
				Double d=this.basicParser.nf.parse(uBets).doubleValue()*-1d;
				wa.chips=d;
				wa.way=Way.POSTRIVER.getName();
				this.bh.actions.add(wa);
				res=true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return res;
	}
}
